package com.beamfield.controller.manage.lab;


import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.beamfield.common.ApiResult;
import com.beamfield.common.CommonUtils;
import com.beamfield.common.PageResult;
import com.beamfield.controller.common.BaseController;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.FileInfo;
import com.beamfield.model.InstrumentInspect;
import com.beamfield.model.InstrumentMaintenance;
import com.beamfield.model.InstrumentMeasure;
import com.beamfield.model.Lab;
import com.beamfield.model.LabInstrument;
import com.beamfield.model.LabUnit;
import com.beamfield.service.manage.lab.LabService;
import com.beamfield.service.manage.lab.ManageService;
import com.beamfield.service.manage.operator.ManagerInfoService;
import com.beamfield.service.manage.sys.DictonaryService;
import com.beamfield.service.manage.sys.FileService;

/**
 * 试验室管理
 */
@Controller
@RequestMapping("/cms/lab/build")
public class LabBuildController extends BaseController{

    @Value("${fileRootUrl}")
    private String fileRootUrl;
    @Value("${session.beam}")
    private String beam;
    @Value("${session.user}")
    private String user;

    @Autowired
    private DictonaryService dictonaryService;
    @Autowired
    private FileService fileService;
    @Autowired
    private LabService labService;
    @Autowired
    private ManagerInfoService managerInfoService;
    @Autowired
    private ManageService manageService;

    @RequestMapping(value = "/base", method = RequestMethod.GET)
    public ModelAndView base() {
        return new ModelAndView();
    }

    @RequestMapping(value = "/organization", method = RequestMethod.GET)
    public ModelAndView organization() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/lab_auth", method = RequestMethod.GET)
    public ModelAndView labAuth() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/lab_unit", method = RequestMethod.GET)
    public ModelAndView labUnit() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/edit_lab_unit", method = RequestMethod.GET)
    public ModelAndView editLabUnit() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/edit_lab_auth", method = RequestMethod.GET)
    public ModelAndView editLabAuth() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/lab_cca", method = RequestMethod.GET)
    public ModelAndView labCca() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/ins_build", method = RequestMethod.GET)
    public ModelAndView insBuild() {
        return new ModelAndView();
    }
    /**
     * 人员管理
     */
    @RequestMapping(value = "/peopleManage", method = RequestMethod.GET)
    public ModelAndView peopleManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/editManagerInfo", method = RequestMethod.GET)
    public ModelAndView editManagerInfo() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/managerInfoDetail", method = RequestMethod.GET)
    public ModelAndView managerInfoDetail() {
        return new ModelAndView();
    }
    /**
     * 设备仪器管理
     */
    @RequestMapping(value = "/instrumentManage", method = RequestMethod.GET)
    public ModelAndView instrumentManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/editInstrument", method = RequestMethod.GET)
    public ModelAndView editInstrument() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/instrumentDetail", method = RequestMethod.GET)
    public ModelAndView instrumentDetail() {
        return new ModelAndView();
    }
    /**
     * 维修保养管理
     */
    @RequestMapping(value = "/maintenanceManage", method = RequestMethod.GET)
    public ModelAndView maintenanceManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/editMaintenance", method = RequestMethod.GET)
    public ModelAndView editMaintenance() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/maintenanceDetail", method = RequestMethod.GET)
    public ModelAndView maintenanceDetail() {
        return new ModelAndView();
    }
    /**
     * 计量管理
     */
    @RequestMapping(value = "/measureManage", method = RequestMethod.GET)
    public ModelAndView measureManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/editMeasure", method = RequestMethod.GET)
    public ModelAndView addMeasure() {
        return new ModelAndView();
    }
    /**
     * 期间核查管理
     */
    @RequestMapping(value = "/inspectManage", method = RequestMethod.GET)
    public ModelAndView inspectManage() {
        return new ModelAndView();
    }
    @RequestMapping(value = "/editInspect", method = RequestMethod.GET)
    public ModelAndView editInspect() {
        return new ModelAndView();
    }

    /**
     * 保存试验室资质审批
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveLabUnit",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult saveLabUnit(@RequestParam("labUnitJson")String labUnitJson,  HttpServletRequest request){
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        if(StringUtils.isEmpty(labUnitJson)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try {
            LabUnit labUnit = JSON.parseObject(labUnitJson, LabUnit.class);
            result = labService.saveLabUnit(userId, beamId, labUnit);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        if (result == 0) {
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        } else {
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "保存成功");
        }
    }

    /**
     * 获取试验室单位基本信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/getLabUnit",method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getLabUnit(HttpServletRequest request){
        Long beamId = super.getBeamId(request);
        String unitNo = request.getParameter("unitNo");
        if(StringUtils.isEmpty(unitNo)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        LabUnit labUnit = labService.getLabUnit(beamId, unitNo);
        return new ApiResult(labUnit);
    }
    /**
     * 获取试验室基本信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/getLab",method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getLab(HttpServletRequest request){
        Long beamId = super.getBeamId(request);
        String id = request.getParameter("id");
        Lab lab = labService.getLab(beamId, id);
        return new ApiResult(lab);
    }

    /**
     * 上传组织结构图
     *
     * @param file_id
     * @return
     */
    @RequestMapping("/saveOrganizationImg")
    @ResponseBody
    public ApiResult saveOrganizationImg(Long file_id, HttpServletRequest request) {
        Long beam_id = super.getBeamId(request);
        try {
            Lab lab = manageService.selectByBeam_id(beam_id);
            if(lab!=null){
                FileInfo fileInfo = fileService.getFileById(file_id);
                if(fileInfo!=null){
                    lab.setOrganization_img(CommonUtils.getFielUrl(fileInfo));
                    manageService.updateLab(lab);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult("1", "服务器异常！");
        }
        return new ApiResult("2", "上传成功！");
    }

    /**
     * 保存试验室资质审批
     * @param request
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/saveLabAcptFile",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult saveLabAcptFile(@RequestParam("id") String id,
                             HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile multipartFile){
        Long userId = super.getUserId(request);
        if(StringUtils.isEmpty(id) || multipartFile == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try {
            long fileId = super.saveFile((CommonsMultipartFile) multipartFile);
            result = labService.saveLabAcptFile(userId, id, fileId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        if (result == 0) {
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        } else {
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "保存成功");
        }
    }

    /**
     * 删除试验室制度建设文件
     * @param request
     * @return
     */
    @RequestMapping(value = "/delInsBuildFile", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult delInsBuildFile(HttpServletRequest request){
        String id = request.getParameter("id");
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        if(id == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try {
            result = labService.delInsBuildFile(userId, beamId,  id);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        if (result == 0) {
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        } else {
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "删除成功");
        }
    }
    /**
     * 获取试验室制度建设文件
     * @param request
     * @return
     */
    @RequestMapping(value = "/readInsBuildFileData", method = RequestMethod.GET)
    @ResponseBody
    public PageResult readInsBuildFileData(HttpServletRequest request){
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        Long beamId = super.getBeamId(request);
        return labService.getInsBuildFileData(beamId, offset, limit);
    }
    /**
     * 保存试验室制度建设文件
     * @param request
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/saveInsBuildFile",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult saveInsBuildFile(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile multipartFile){
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        if(multipartFile == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try {
            long fileId = super.saveFile((CommonsMultipartFile) multipartFile);
            result = labService.saveInsBuildFile(userId, beamId,  fileId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        if (result == 0) {
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        } else {
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "保存成功");
        }
    }

    /**
     * 保存试验室资质审批
     * @param labJson
     * @param request
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/saveLab",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult saveLab(@RequestParam("labJson") String labJson,
                                          HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile multipartFile){
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        if(StringUtils.isEmpty(labJson)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try {
            Lab lab = JSON.parseObject(labJson, Lab.class);
            if(multipartFile != null) {
                long fileId = super.saveFile((CommonsMultipartFile) multipartFile);
                lab.setAuth_file(fileId);
            }
            lab.setExtend1("1");
            result = labService.saveLab(userId, beamId, lab);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        if (result == 0) {
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        } else {
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "保存成功");
        }
    }

    /***
     * 更新试验室审批状态
     * @param id
     * @param state
     * @return
     */
    @RequestMapping(value = "/updateLabState", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult updateLabState(Integer id, String state){
        labService.updateLabState(id, state);
        return new ApiResult();
    }


    /**
     * 获取管理人员列表
     * @param offset
     * @param limit
     * @param name
     * @param identity
     * @return
     */
    @RequestMapping("/getLabManagerList")
    @ResponseBody
    public PageResult getManagerInfoList(Integer offset, Integer limit,String identity,String name, String unit, String presasg, HttpSession session){
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.getManagerInfoList( offset,  limit, identity, name,beam_id,"990107", unit, presasg);
    }

    /**
     * 上移
     * @param manager_id
     * @param session
     * @return
     * @author anruoxin
     * 2019年4月12日
     */
    @RequestMapping("/upLevel")
    @ResponseBody
    public ApiResult upLevel(Long manager_id, HttpSession session){
        Long beam_id = (Long) session.getAttribute(beam);
        ApiResult apiResult=new ApiResult();
        if (manager_id != null) {
        	return labService.upLevel(manager_id, beam_id);
        }else  {
            apiResult.setMessage("未获取到人员");
            apiResult.setCode("500");
            return  apiResult;
        }
    }

    /**
     * 下移
     * @param manager_id
     * @param session
     * @return
     * @author anruoxin
     * 2019年4月12日
     */
    @RequestMapping("/downLevel")
    @ResponseBody
    public ApiResult downLevel(Long manager_id, HttpSession session){
        Long beam_id = (Long) session.getAttribute(beam);
        ApiResult apiResult=new ApiResult();
        if (manager_id != null) {
        	return labService.downLevel(manager_id, beam_id);
        }else  {
            apiResult.setMessage("未获取到人员");
            apiResult.setCode("500");
            return  apiResult;
        }
    }

    /**
     * 删除试验人员
     * @return
     */
    @RequestMapping("/delLabManager")
    @ResponseBody
    public ApiResult delLabManager(String id){
     ApiResult apiResult=new ApiResult();
       if (StringUtils.isNotBlank(id)) {
           return labService.delLabManager(id);
       }else  {
           apiResult.setMessage("未获取到删除的管理人员");
           apiResult.setCode("500");
           return  apiResult;
       }
    }
    /**
     * 获取仪器设备列表
     * @param offset
     * @param limit
     * @param instr_name
     * @param manufacturer
     * @return
     */
    @RequestMapping("/getLabInstrumentList")
    @ResponseBody
    public PageResult getLabInstrumentList(Integer offset, Integer limit, String instr_name, String manufacturer, String storage_location, HttpSession session){
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.getLabInstrumentList( offset, limit, instr_name, manufacturer,beam_id, storage_location);
    }

    /**
     * 导入设备仪器
     * @param request
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/importInstrument", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult importInstrument(HttpServletRequest request, @RequestParam("excelFile") MultipartFile multipartFile) {
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);

        if (multipartFile == null) {
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        try {
            long fileId = super.saveFile((CommonsMultipartFile) multipartFile);
            InputStream in = multipartFile.getInputStream();
            byte[] data = IOUtils.toByteArray(in);
            Workbook wb = null;
            FormulaEvaluator formulaEvaluator;
            try {
                wb = new HSSFWorkbook(new ByteArrayInputStream(data));
                formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);
            } catch (Exception e) {
                wb = new XSSFWorkbook(new ByteArrayInputStream(data));
                formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb);
            }
            return labService.importInstrument(wb,fileId,userId,beamId,formulaEvaluator);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 获取仪器设备编号下拉框
     */
    @RequestMapping("/getAllLabInstrument")
    @ResponseBody
    public List<LabInstrument> getAllLabInstrument(HttpSession session){
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.getAllLabInstrument(beam_id);
    }
    /**
     * 删除仪器设备
     * @return
     */
    @RequestMapping("/delLabInstrument")
    @ResponseBody
    public ApiResult delLabInstrument(String id){
        ApiResult apiResult=new ApiResult();
        if (StringUtils.isNotBlank(id)) {
            return labService.delLabInstrument(id);
        }else  {
            apiResult.setMessage("未获取到删除的仪器设备");
            apiResult.setCode("500");
            return  apiResult;
        }
    }

    @RequestMapping("/getInstrumentInfo")
    @ResponseBody
    public ApiResult getInstrumentInfo(Long id,Boolean flag, HttpSession session) {
        ApiResult apiResult = new ApiResult();

        Map<String, Object> map = new HashMap<String, Object>();
        LabInstrument labInstrument = labService.getInstrumentInfo(id,flag);
        if(labInstrument!=null){
            FileInfo fileInfo = fileService.getFileById(labInstrument.getFile_id());
            if(fileInfo!=null){
                map.put("file_id", fileInfo.getFileid());
                map.put("file_url", CommonUtils.getFielUrl(fileInfo));
                map.put("fileName", fileInfo.getFormer_name());
            }
        }
        map.put("labInstrument", labInstrument);
        apiResult.setResult(map);
        return apiResult;
    }

    /**
     * 新增或编辑仪器设备
     *
     * @param object
     * @param text 操作流程富文本
     * @return
     */
    @RequestMapping("/doEditInstrument")
    @ResponseBody
    public ApiResult doEditInstrument(String object,String text, HttpSession session) {
        Long user_id = (Long) session.getAttribute(user);
        Long beam_id = (Long) session.getAttribute(beam);
        LabInstrument labInstrument = JSON.parseObject(object,LabInstrument.class);
        labInstrument.setOperating_procedure(text);

        labInstrument.setUpdater(user_id);
        labInstrument.setUpdatetime(new Date());
        labInstrument.setBeam_id(beam_id);

        try {
            //新增
            if (labInstrument.getId() == null) {
                labInstrument.setOperator(user_id);
                labInstrument.setAddtime(new Date());
                return labService.insertInstrument(labInstrument);
            }
            //编辑
            else {
                labService.updateInstrument(labInstrument);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult("1", "服务器异常！");
        }
        return new ApiResult("2", "成功！");
    }
    /**
     * 获取存在维修记录的仪器列表
     * @param offset
     * @param limit
     * @param instr_name
     * @param instr_no
     * @return
     */
    @RequestMapping("/getListWithMaintenance")
    @ResponseBody
    public PageResult getMaintenanceList(Integer offset, Integer limit, String instr_name, String instr_no, HttpSession session){
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.getListWithMaintenance( offset, limit,instr_name,instr_no,beam_id);
    }

    @RequestMapping("/getLastMaintenanceInfo")
    @ResponseBody
    public ApiResult getLastMaintenanceInfo(Long id, HttpSession session) {
        Long beam_id = (Long) session.getAttribute(beam);
        ApiResult apiResult = new ApiResult();

        Map<String, Object> map = new HashMap<String, Object>();
        LabInstrument labInstrument = labService.getInstrumentInfo(id,false);
        InstrumentMaintenance instrumentMaintenance = labService.getLastMaintenanceInfo(id,beam_id);
        if(labInstrument!=null) {
            map.put("instr_no", labInstrument.getInstr_no());
            map.put("instr_name", labInstrument.getInstr_name());
            map.put("instr_model", labInstrument.getInstr_model());
        }
        map.put("lastMaintenance", instrumentMaintenance);
        apiResult.setResult(map);
        return apiResult;
    }
    /**
     * 获取某个仪器的维修记录列表
     * @param offset
     * @param limit
     * @param id
     * @return
     */
    @RequestMapping("/getMaintenanceList")
    @ResponseBody
    public PageResult getMaintenanceList(Integer offset, Integer limit,Long id, HttpSession session) {
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.getMaintenanceList(offset,limit,id,beam_id);

    }
    /**
     * 新增或编辑维修记录
     *
     * @param object
     * @param type 维修保养内容
     * @return
     */
    @RequestMapping("/doEditMaintenance")
    @ResponseBody
    public ApiResult doEditMaintenance(String object,String type, String instrNos, HttpSession session) {
        Long user_id = (Long) session.getAttribute(user);
        Long beam_id = (Long) session.getAttribute(beam);
        InstrumentMaintenance instrumentMaintenance = JSON.parseObject(object,InstrumentMaintenance.class);
        instrumentMaintenance.setMaint_content(type);

        instrumentMaintenance.setUpdater(user_id);
        instrumentMaintenance.setUpdatetime(new Date());
        instrumentMaintenance.setBeam_id(beam_id);

        try {
            //新增
            instrumentMaintenance.setOperator(user_id);
            instrumentMaintenance.setAddtime(new Date());
            labService.insertMaintenance(instrumentMaintenance, instrNos);

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult("1", "服务器异常！");
        }

        return new ApiResult("2", "成功！");
    }
    /**
     * 获取计量情况列表
     * @param offset
     * @param limit
     * @param instr_name
     * @param manufacturer
     * @return
     */
    @RequestMapping("/getMeasureList")
    @ResponseBody
    public PageResult getMeasureList(Integer offset, Integer limit, String instr_name, String manufacturer, HttpSession session){
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.getMeasureList(offset, limit,instr_name,manufacturer,beam_id);
    }
    @RequestMapping("/getMeasureInfo")
    @ResponseBody
    public ApiResult getMeasureInfo(Long id, HttpSession session) {
        ApiResult apiResult = new ApiResult();

        Map<String, Object> map = new HashMap<String, Object>();
        InstrumentMeasure instrumentMeasure = labService.getMeasureInfo(id);
        map.put("instrumentMeasure", instrumentMeasure);
        apiResult.setResult(map);
        return apiResult;
    }
    /**
     * 新增/编辑计量情况（同时操作核查情况表）
     * @return
     */
    @RequestMapping("/doEditMeasure")
    @ResponseBody
    public ApiResult doAddMeasure(String object, @RequestParam(required = false) String instrNos, Integer type, HttpSession session) {
        Long user_id = (Long) session.getAttribute(user);
        Long beam_id = (Long) session.getAttribute(beam);

        InstrumentMeasure instrumentMeasure = JSON.parseObject(object, InstrumentMeasure.class);

        instrumentMeasure.setUpdater(user_id);
        instrumentMeasure.setUpdatetime(new Date());
        instrumentMeasure.setBeam_id(beam_id);

        try {
            if(Objects.equals(type, 1)){
                Arrays.stream(instrNos.split(",")).forEach(c->{
                    //新增
                    instrumentMeasure.setInstr_no(c);
                    instrumentMeasure.setOperator(user_id);
                    instrumentMeasure.setAddtime(new Date());
                    instrumentMeasure.setId(null);
                    Long measure_id = labService.insertMeasure(instrumentMeasure);
                    //插入核查表
                    if(instrumentMeasure.getIs_inspect()==1){
                        InstrumentInspect instrumentInspect = new InstrumentInspect();
                        instrumentInspect.setInstr_no(instrumentMeasure.getInstr_no());
                        instrumentInspect.setOperator(user_id);
                        instrumentInspect.setAddtime(new Date());
                        instrumentInspect.setUpdater(user_id);
                        instrumentInspect.setUpdatetime(new Date());
                        instrumentInspect.setBeam_id(beam_id);
                        instrumentInspect.setMeasure_id(measure_id);

                        labService.insertInspect(instrumentInspect);
                    }
                });

            }
            else {
                //编辑
                labService.updateMeasure(instrumentMeasure);
                if(instrumentMeasure.getIs_inspect()==1){
                    //修改为需要时如不存在核查情况则新增
                    if(labService.getInspectByMeasure_id(instrumentMeasure.getId())==null){
                        InstrumentInspect instrumentInspect = new InstrumentInspect();
                        instrumentInspect.setInstr_no(instrumentMeasure.getInstr_no());
                        instrumentInspect.setOperator(user_id);
                        instrumentInspect.setAddtime(new Date());
                        instrumentInspect.setUpdater(user_id);
                        instrumentInspect.setUpdatetime(new Date());
                        instrumentInspect.setBeam_id(beam_id);
                        instrumentInspect.setMeasure_id(instrumentMeasure.getId());

                        labService.insertInspect(instrumentInspect);
                    }
                }
                else{
                    //修改为不需要时如存在核查情况则删除
                    if(labService.getInspectByMeasure_id(instrumentMeasure.getId())!=null){
                        labService.deleteInspect(labService.getInspectByMeasure_id(instrumentMeasure.getId()).getId());
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult("1", "服务器异常！");
        }

        return new ApiResult("2", "成功！");
    }
    /**
     * 获取核查情况列表
     * @param offset
     * @param limit
     * @param instr_name
     * @param manufacturer
     * @return
     */
    @RequestMapping("/getInspectList")
    @ResponseBody
    public PageResult getInspectList(Integer offset, Integer limit, String instr_name, String manufacturer, HttpSession session){
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.getInspectList(offset, limit,instr_name,manufacturer,beam_id);
    }

    @RequestMapping("/getInspectInfo")
    @ResponseBody
    public ApiResult getInspectInfo(Long id, HttpSession session) {
        ApiResult apiResult = new ApiResult();

        Map<String, Object> map = new HashMap<String, Object>();
        InstrumentInspect instrumentInspect = labService.getInspectInfo(id);
        map.put("instrumentInspect", instrumentInspect);
        apiResult.setResult(map);
        return apiResult;
    }
    /**
     * 编辑核查情况
     *
     * @param instrumentInspect
     * @return
     */
    @RequestMapping("/doEditInspect")
    @ResponseBody
    public ApiResult doEditInspect(InstrumentInspect instrumentInspect, HttpSession session) {
        Long user_id = (Long) session.getAttribute(user);
        Long beam_id = (Long) session.getAttribute(beam);

        instrumentInspect.setUpdater(user_id);
        instrumentInspect.setUpdatetime(new Date());
        instrumentInspect.setBeam_id(beam_id);
        try {
            labService.updateInspect(instrumentInspect);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult("1", "服务器异常！");
        }

        return new ApiResult("2", "成功！");
    }
    /**
     * 导出仪器设备台账
     *
     * @param response
     * @param offset
     * @param limit
     * @param instr_name
     * @param manufacturer
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportLabInstrument")
    @ResponseBody
    public String exportLabInstrument(HttpServletResponse response, Integer offset, Integer limit, String instr_name, String manufacturer, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
         return labService.exportLabInstrument(response,offset,limit,instr_name,manufacturer,beam_id);
    }
    /**
     * 导出仪器设备简历
     * @return
     */

    @RequestMapping(value = "/exportLabInstrumentDetail")
    @ResponseBody
    public ApiResult exportLabInstrumentDetail(Long id,HttpServletResponse response,HttpServletRequest request){

        return labService.exportLabInstrumentDetail(id,response);
    }

    /**
     * 导出仪器设备维修保养
     *
     * @param response
     * @param offset
     * @param limit
     * @param instr_name
     * @param instr_no
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportInstrumentWithMaintenance")
    @ResponseBody
    public String exportInstrumentWithMaintenance(HttpServletResponse response, Integer offset, Integer limit, String instr_name, String instr_no, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.exportInstrumentWithMaintenance(response,offset,limit,instr_name,instr_no,beam_id);
    }
    /**
     * 导出仪器设备维修保养记录
     *
     * @param response
     * @param offset
     * @param limit
     * @param id
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportMaintenance")
    @ResponseBody
    public String exportMaintenance(HttpServletResponse response, Integer offset, Integer limit,Long id, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.exportMaintenance(response,offset,limit,id,beam_id);
    }
    /**
     * 导出计量管理情况
     *
     * @param response
     * @param offset
     * @param limit
     * @param instr_name
     * @param manufacturer
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportMeasure")
    @ResponseBody
    public String exportMeasure(HttpServletResponse response, Integer offset, Integer limit,String instr_name, String manufacturer, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.exportMeasure(response,offset,limit,instr_name,manufacturer,beam_id);
    }
    /**
     * 导出期间核查情况
     *
     * @param response
     * @param offset
     * @param limit
     * @param instr_name
     * @param manufacturer
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportInspect")
    @ResponseBody
    public String exportInspect(HttpServletResponse response, Integer offset, Integer limit,String instr_name, String manufacturer, HttpSession session) throws Exception {
        Long beam_id = (Long) session.getAttribute(beam);
        return labService.exportInspect(response,offset,limit,instr_name,manufacturer,beam_id);
    }

    /**
     * 获取试验室参数库
     *
     * @return
     */
    @RequestMapping("/getLabParameterRep")
    @ResponseBody
    public ApiResult getLabParameterRep(HttpSession session, HttpServletRequest request) {
        Long beamId = (Long) session.getAttribute(beam);
        String parameter = request.getParameter("parameter");
        return new ApiResult(labService.getLabParameterRep(beamId, parameter));
    }

    /**
     * 获取试验室制度建设文件列表
     *
     * @param offset
     * @param limit
     * @param classify
     * @return
     */
    @RequestMapping("/listLabSystemFile")
    @ResponseBody
    public PageResult listLabSystemFile(HttpSession session,Integer offset, Integer limit, String classify) {
        Long beamId = (Long) session.getAttribute(beam);
        return labService.listLabSystemFile(offset,limit,classify,beamId);
    }

    /**
     * 保存试验室制度建设文件
     *
     * @param multipartFile
     * @param classify
     */
    @RequestMapping("/saveLabSystemFile")
    @ResponseBody
    public ApiResult saveLabSystemFile(HttpSession session,@RequestParam(value = "file", required = false) MultipartFile multipartFile,String classify) {
        Long userId = (Long) session.getAttribute(user);
        Long beamId = (Long) session.getAttribute(beam);
        try {
            Long fileId = super.saveFile((CommonsMultipartFile) multipartFile);
            labService.saveLabSystemFile(fileId,classify,userId,beamId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        return new ApiResult();
    }

    /**
     * 保存试验室制度建设文件
     *
     * @param id
     */
    @RequestMapping("/delLabSystemFile")
    @ResponseBody
    public ApiResult delLabSystemFile(HttpSession session,Long id) {
        labService.delLabSystemFile(id);
        return new ApiResult();
    }
}
